from com.atzl.ui.WronglySendUI import Ui_Form
from PyQt5 import QtCore
from com.atzl.common.Win import Windows
from com.atzl.common.StatusCode import StatusCode
from com.atzl.common.ActionStates import ActionStates
from com.atzl.functions.accounting.func.Logs import CheckLogs
from com.atzl.functions.customerservice.func.WronglySendDataAnalysis import Datacleansing
from PyQt5.QtCore import QDateTime, QThread, pyqtSignal, QTimer
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *


# 错发报表交互
class WronglySendWindow(QMainWindow, CheckLogs):  # 继承:QMainWindow, CheckLogs
    def __init__(self):
        QMainWindow.__init__(self)
        # 设置为全局小部件
        self.ui = Ui_Form()
        self.data = Datacleansing()
        self.work = work_thread()
        self.m_flag = False
        self.ui.setupUi(self)
        self.h = 0
        self.min = 0
        self.sec = 0
        self.secondSec = 0
        global widgets
        widgets = self.ui
        global the_data
        the_data = self.data


        widgets.dateTimeEdit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        widgets.dateTimeEdit_2.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        widgets.dateTimeEdit_2.setDateTime(QDateTime.currentDateTime())
        widgets.dateTimeEdit.setDateTime(QDateTime.currentDateTime())
        widgets.dateTimeEdit_2.setTime(QtCore.QTime(0, 0, 0))
        widgets.dateTimeEdit.setTime(QtCore.QTime(23, 59, 59))
        widgets.pushButton_2.clicked.connect(self.close_app)  # 关闭应用程序
        widgets.pushButton_3.clicked.connect(self.showMinimized)  # 窗口最小化
        widgets.pushButton_7.clicked.connect(self.rollback_navigation)  # 返回导航页
        widgets.pushButton.clicked.connect(self.work.start)  # 开启子线程
        self.work.select_obj_end.connect(self.obj_end)  # 触发结束线程信号
        self.work.select_obj_start.connect(self.obj_start)  # 触发启动线程信号
        self.work.select_obj_error.connect(self.obj_error)  # 触发启动线程信号
        widgets.pushButton_8.clicked.connect(self.open_the_files)  # 返回导航页

        self.timer = QTimer()
        self.timer.setInterval(10)
        self.timer.timeout.connect(self.onTimerOut)



    def startTimer(self):
        self.sec = 0
        self.min = 0
        texttime = "耗时: 00:00:00:00"
        widgets.label_8.setText(texttime)
        widgets.label_8.clear()
        # 设置计时间隔并启动，每隔1000毫秒（1秒）发送一次超时信号，循环进行
        self.timer.start()
        widgets.pushButton.setEnabled(False)

    def endTimer(self):
        self.timer.stop()
        widgets.pushButton.setEnabled(True)

    def onTimerOut(self):
        self.secondSec += 1
        text_h = self.text_format(self.h)
        text_min = self.text_format(self.min)
        text_sec = self.text_format(self.sec)
        text_secondSec = self.text_format(self.secondSec)
        timetext = f"耗时: {text_h}:{text_min}:{text_sec}:{text_secondSec}"
        widgets.label_8.setText(timetext)


        if self.secondSec == 100:
            self.secondSec = 0
            self.sec += 1

        if self.sec == 60:
            self.sec = 0
            self.min += 1

        if self.min == 60:
            self.min = 0
            self.h += 1

    def text_format(self, time):
        if time < 10:
            return f"0{time}"
        else:
            return f"{time}"


    def rollback_navigation(self):
        self.hide()
        Windows.NAVIGATION_WIN.show()
        Windows.NAVIGATION_WIN.show_anim()
        self.logs_in(ActionStates.ROLLBACKNAVIGATION)


    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(QtCore.Qt.OpenHandCursor))  # 更改鼠标图标


    def mouseMoveEvent(self, QMouseEvent):
        if QtCore.Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()


    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(QtCore.Qt.ArrowCursor))

    # 设置线程启动时界面交互
    def obj_start(self):
        self.startTimer()
        self.to_message("正在汇总🥰")
        self.logs_in(ActionStates.STARTCREATERBILLBUTTON)  # 回传用户行为

    def obj_end(self):
        self.endTimer()
        self.to_message("完成报表🥰")
        self.logs_in(ActionStates.FINISH_WRONGLYTABLE)  # 回传用户行为

    def obj_error(self):
        self.work.terminate()
        self.endTimer()
        self.to_message("未知错误!")
        self.logs_in(ActionStates.FINISH_WRONGLYTABLE)  # 回传用户行为

    # 弹出消息提示框
    def to_message(self, text):
        Windows.MESSAGE_WIN.set_message(text)  # 设置提示内容并弹出提示框

    # 打卡文件目录
    def open_the_files(self):
        # 判断文件目录是否打开成功
        if the_data.open_files() is False:  # 返回False提示找不到文件路径
            self.to_message(StatusCode.MISSING_DIRPATH)  # 提示消息
            self.logs_in(ActionStates.HINTDONTHAVEDIR)  # 回传用户行为
        else:  # 返回True不做提示
            self.logs_in(ActionStates.OPENDWRONGEPOSITDIR)  # 回传用户行为

    # 关闭应用程序
    def close_app(self):
        self.logs_in(ActionStates.CLOSEAPPLICATION)
        self.close()

# 创建子线程
class work_thread(QThread):  # 继承:QThread
    select_obj_end = pyqtSignal()  # 创建线程结束信号对象
    select_obj_start = pyqtSignal()  # 创建线程启动信号对象
    select_obj_error = pyqtSignal()  # 未知错误信号对象

    def __init__(self):
        super().__init__()

    # 重写run方法
    def run(self):
        self.select_obj_start.emit()  # 发射启动信号
        dispose_data = the_data.how_get_data(self.get_start_datetime(),
                                             self.get_end_datetime(),
                                             self.get_floor(),
                                             self.get_field(),
                                             self.get_sorting(),
                                             self.get_name())
        # 判断账单制作情况
        if dispose_data == StatusCode.SUBTASK_FINISH:  # 正常结束时
            self.select_obj_end.emit()  # 发射正常结束信号
        elif dispose_data == StatusCode.UNKONWN_ERROR:
            self.select_obj_error.emit()  # 发射未知错误信号

    # 获取起始时间
    def get_start_datetime(self):
        datetime = widgets.dateTimeEdit_2.dateTime()
        datetime = datetime.toString(widgets.dateTimeEdit.displayFormat())
        return datetime

    # 获取结束时间
    def get_end_datetime(self):
        datetime = widgets.dateTimeEdit.dateTime()
        datetime = datetime.toString(widgets.dateTimeEdit.displayFormat())
        return datetime

    # 获取排序方式
    def get_sorting(self):
        sorting = widgets.comboBox_3.currentText()
        return sorting

    # 获取排序方式
    def get_field(self):
        fieldname = widgets.comboBox_2.currentText()
        return fieldname

    # 获取设备层数
    def get_floor(self):
        floor = widgets.comboBox.currentText()
        if floor == "1层":
            floor = 1
        elif floor == "2层":
            floor = 2
        return floor

    # 获取好友名称
    def get_name(self):
        name = widgets.lineEdit.text()
        return name